package oakclub.pool;

import nf.fr.eraasoft.pool.PoolException;
import nf.fr.eraasoft.pool.PoolableObjectBase;
import oakclub.thrift.scribe.scribe;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ScribeClientPool extends PoolableObjectBase<scribe.Client>
{
    private String host;
    private int port;
    private final Logger logger = LoggerFactory.getLogger(ScribeClientPool.class);

    public ScribeClientPool(String host, int port)
    {
        this.host = host;
        this.port = port;
    }

    @Override
    public scribe.Client make() throws PoolException
    {
        TTransport transport = new TFramedTransport(new TSocket(this.host, this.port));
        try
        {
            transport.open();
        }
        catch(Exception e)
        {
            this.logger.error("scribe client init failed", e);
            return null;
        }
        TProtocol protocol = new TBinaryProtocol(transport, false, false);
        scribe.Client client = new scribe.Client(protocol);
        return client;
    }

    @Override
    public void destroy(scribe.Client scribeClient)
    {
        TProtocol protocol = scribeClient.getInputProtocol();
        if(protocol != null)
        {
            TTransport transport = protocol.getTransport();
            if(transport != null && transport.isOpen())
            {
                transport.close();
            }
        }
    }

    @Override
    public void activate(scribe.Client scribeClient) throws PoolException
    {

    }
}